/**
 * 邀请页面
 * author wim
 */
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_saver/image_saver.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/base/application.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/LoadingUtil.dart';
import 'package:panda/util/SignUtil.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/entity/banner_entity.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:wechat_kit/wechat_kit.dart';

class InviteFriend2Page extends StatefulWidget {
  InviteFriend2Page({Key key}) : super(key: key);

  _InviteFriend2PageState createState() => _InviteFriend2PageState();
}

class _InviteFriend2PageState extends State<InviteFriend2Page> {
  ScrollController _scrollController = new ScrollController();
  static const jumpPlugin = const MethodChannel('samples.flutter.io/battery');
  String uid = "1", code = "888888";
  String img = "";
  List<GlobalKey> globalKeys = new List();
  // final _imageSaver = ImageSaver();
  int posotion = -1;
  List<BannerModelData> bannerList = List();
  StreamSubscription<WechatSdkResp> _share;
  Wechat _wechat = Wechat()
    ..registerApp(appId: WX_APPID, universalLink: WECHAT_UNIVERSAL_LINK);
  bool isShow = true;
  Offset pointerStart;
  Offset pointerEnd;
//获取屏幕宽度
  double screenWidth = 0.0;

  double touchRangeX = 0.0;

  int lastPage = 0;
  int cueerntPage = 0;
  double touchRangeY = 0.0;

  double nextOffset = 0.0;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(UID).then((value) {
      uid = value ?? "1";
      loadBanner();
    });
    code = APPLIC.userInfoMap['user_msg']['auth_code'];
    checkWx();
  }

  PointerUpEventListener getPonitUpListenerInHorizontal() {
    return (event) {
      pointerEnd = event.position;
      touchRangeX = pointerStart.dx - pointerEnd.dx;
      touchRangeY = pointerStart.dy - pointerEnd.dy;
      //所有的操作必须要满足滑动距离>10才算是滑动
      if (touchRangeX.abs() < 10) {
        nextOffset = screenWidth * lastPage;
        scrollAnimToOffset(_scrollController, nextOffset, () {
          if (lastPage < 0) {
            lastPage = 0;
          }
        });
        return;
      }
      //纵向操作大于横向操作三倍视为纵向操作
      //这个判断拦截只有在纵向操作距离大于20.0的时候才生效
      if (touchRangeX.abs() < touchRangeY.abs() && touchRangeY > 20) {
        nextOffset = screenWidth * lastPage;
        scrollAnimToOffset(_scrollController, nextOffset, () {
          if (lastPage < 0) {
            lastPage = 0;
          }
        });
        return;
      }

      //如果滑动小于当前屏幕1/8，那么就回弹复原，超过则移动到下一页
      //跳转到下一页或者上一页或者不动
      if (touchRangeX > screenWidth / 4) {
        nextOffset = screenWidth * (lastPage + 1);
        scrollAnimToOffset(_scrollController, nextOffset, () {
          lastPage++;
          cueerntPage = lastPage;
          if (lastPage >= bannerList.length - 1) {
            lastPage = bannerList.length - 1;
            cueerntPage = lastPage;
          }
        });
      } else if (touchRangeX < -1 * screenWidth / 8) {
        nextOffset = screenWidth * (lastPage - 1);
        scrollAnimToOffset(_scrollController, nextOffset, () {
          lastPage--;
          cueerntPage = lastPage;
          if (lastPage < 0) {
            lastPage = 0;
            cueerntPage = lastPage;
          }
        });
      } else {
        scrollAnimToOffset(_scrollController, screenWidth * lastPage, null);
      }
    };
  }

  void scrollAnimToOffset(ScrollController controller, double offset,
      void Function() onScrollCompleted) {
    controller
        .animateTo(offset,
            duration: Duration(
              milliseconds: 200,
            ),
            curve: Curves.easeIn)
        .then((v) {
      if (onScrollCompleted != null) {
        onScrollCompleted();
      }
    }).catchError((e) {
      print(e);
    });
    print(cueerntPage);
  }

  checkWx() async {
    if (await _wechat.isInstalled()) {
      _share = _wechat.shareMsgResp().listen(_listenShareMsg);
      setState(() {
        isShow = false;
      });
    } else {
      setState(() {
        isShow = true;
      });
    }
  }

  Future loadBanner() async {
    Map map = new Map();
    map['cat_id'] = "4";
    map['sign_type'] = SignType.GET_BANNER_LIST;
    Response<String> response =
        await HttpUtil().post(Api.GETBANNER, data: getSign(map));
    Map userMap = json.decode(response.data);
    BannerModelEntity bannerEntity = new BannerModelEntity.fromJson(userMap);
    int code = userMap['code'];
    if (code == 1 && mounted) {
      if (bannerEntity.data.length > 0) {
        bannerList.addAll(bannerEntity.data);
        for (int i = 0; i < bannerList.length; i++) {
          globalKeys.add(GlobalKey());
        }
        setState(() {
          posotion = 0;
          // img = Api.BaseUrl + bannerEntity.data[0].img;
        });
      }
    }
  }

  @override
  void dispose() {
    if (_share != null) {
      _share.cancel();
    }
    super.dispose();
  }

  _capturePng(plat) async {
    try {
      RenderRepaintBoundary boundary =
          globalKeys[cueerntPage].currentContext.findRenderObject();
      var image = await boundary.toImage(pixelRatio: 3.0);
      ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List pngBytes = byteData.buffer.asUint8List();
      _capturePath(pngBytes,
          Platform.isIOS ? pngBytes : pngBytes.buffer.asInt8List(), plat);
      Navigator.of(context).pop(1);
      return pngBytes;
    } catch (e) {
      Navigator.of(context).pop(1);
      print(e);
    }
    return null;
  }

  _capturePath(pngBytes, byteData, plat) async {
    String fileName = DateTime.now().millisecondsSinceEpoch.toString() + ".png";
    if (Platform.isAndroid) {
      var status = await Permission.storage.status;

      if (status.isGranted) {
        Directory documentsDirectory = await getExternalStorageDirectory();
        String path = documentsDirectory.path+"/xiongmao";
        bool has= await Directory(path).exists();
        if (!has) {
          await Directory(path).create();
        }
        File file = await File(path + "/$fileName").writeAsBytes(pngBytes);
        if (plat != null) {
          await _wechat.shareImage(
            scene: plat,
            imageUri: Uri.file(file.path),
          );
        } else {
          String result = await ImageGallerySaver.saveFile(path + "/$fileName");
          if (result!=null) {
            Fluttertoast.showToast(msg: "保存成功");
          } else {
            Fluttertoast.showToast(msg: "保存失败");
          }
        }
      } else {
        await Permission.storage.request();
      }
    } else {
      Directory documentsDirectory = await getApplicationDocumentsDirectory();
      String path = documentsDirectory.path;
      File(path + "/$fileName").writeAsBytes(pngBytes);

      // final res = await _imageSaver.saveImage(
      // imageBytes: pngBytes, imageName: fileName, directoryName: path);
      // File file = File(path + "/$fileName");
      final result = await ImageGallerySaver.saveFile(path + "/$fileName");
      print(result);
      if (result) {
        // File file = File(path + "/$fileName");
        // print(file.existsSync());

        await _wechat.shareImage(
          scene: plat,
          imageUri: Uri.file(path + "/$fileName"),
        );
      } else {
        Fluttertoast.showToast(msg: "分享失败");
      }
      // } else {
      //   Fluttertoast.showToast(msg: "失败");
      // }
    }
  }

  @override
  Widget build(BuildContext context) {
    screenWidth = MediaQuery.of(context).size.width;
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return new Scaffold(
      appBar: new AppBar(
        title: Text(
          '分享APP',
          style: TextStyle(
              color: black,
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
        ),
        backgroundColor: white,
        elevation: 0.2,
        brightness: Brightness.light,
        iconTheme: new IconThemeData(color: black_99),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: Container(
              child: Listener(
                onPointerDown: (event) {
                  pointerStart = event.position;
                },
                onPointerUp: getPonitUpListenerInHorizontal(),
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  controller: _scrollController,
                  physics: BouncingScrollPhysics(),
                  itemBuilder: (BuildContext context, int index) {
                    return Container(
                      width: MediaQuery.of(context).size.width,
                      alignment: Alignment.center,
                      // padding: EdgeInsets.fromLTRB(
                      //     ScreenUtil.getInstance().setHeight(DP_60),
                      //     0,
                      //     ScreenUtil.getInstance().setHeight(DP_60),
                      //     0),
                      child: RepaintBoundary(
                        key: globalKeys[index],
                        child: Container(
                          child: new Stack(
                            children: <Widget>[
                              ClipRRect(
                                borderRadius: BorderRadius.circular(10.0),
                                child: posotion == -1
                                    ? Text('')
                                    : CachedNetworkImage(
                                        imageUrl: Api.ImgBaseUrl +
                                            bannerList[index].img,
                                        width: ScreenUtil.getInstance()
                                                .setHeight(820) *
                                            750 /
                                            1334,
                                        height: ScreenUtil.getInstance()
                                            .setHeight(820),
                                      ),
                              ),
                              Positioned(
                                left: ScreenUtil.getInstance().setHeight(820) *
                                        750 /
                                        1334 /
                                        2 -
                                    ScreenUtil.getInstance().setHeight(170) / 2,
                                top: ScreenUtil.getInstance().setHeight(503),
                                child: QrImage(
                                  data:'https://a.app.qq.com/o/simple.jsp?pkgname=com.dmooo.panda',
                                  version: QrVersions.auto,
                                  size: ScreenUtil.getInstance().setHeight(170),
                                  gapless: true,
                                ),
                              ),
                              //  Positioned(
                              //   left: ScreenUtil.getInstance().setHeight(820) *
                              //           750 /
                              //           1334 /
                              //           2 -10-
                              //       ScreenUtil.getInstance().setHeight(150) / 2,
                              //   bottom: ScreenUtil.getInstance().setHeight(45),
                              //   child:Text('邀请码:',style:TextStyle(color:Colors.white70,fontSize:ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE))),
                              // ),
                              //   Positioned(
                              //   left: ScreenUtil.getInstance().setHeight(820) *
                              //           750 /
                              //           1334 /
                              //           2 -
                              //       ScreenUtil.getInstance().setHeight(150) / 2+35,
                              //   bottom: ScreenUtil.getInstance().setHeight(45),
                              //   child:Text('$code',style:TextStyle(color:white,fontSize:ScreenUtil.getInstance().setSp(BIG_FONT_SIZE-4))),
                              // )
                            ],
                          ),
                        ),
                      ),
                    );
                  },
                  itemCount: bannerList.length,
                ),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.fromLTRB(
                0, 0, 0, ScreenUtil.getInstance().setHeight(DP_80)),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new Container(
                  height: ScreenUtil.getInstance().setHeight(DP_60),
                  decoration: new BoxDecoration(
                      border: Border.all(color: mainColor, width: 1),
                      borderRadius: BorderRadius.circular(5)),
                  padding: EdgeInsets.fromLTRB(
                      ScreenUtil.getInstance().setHeight(DP_30),
                      0,
                      ScreenUtil.getInstance().setHeight(DP_30),
                      0.0),
                  child: new FlatButton(
                    child: new Padding(
                      padding: EdgeInsets.all(0.0),
                      child: new Text(
                        "复制链接",
                        style: new TextStyle(
                            color: mainColor,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE)),
                      ),
                    ),
                    onPressed: () {
                      ClipboardData data = new ClipboardData(
                          text:'https://a.app.qq.com/o/simple.jsp?pkgname=com.dmooo.panda'); //Api.BaseUrl +"/wap.php/UserAccount/register/referrer_id/$uid"
                      Clipboard.setData(data);
                      Fluttertoast.showToast(msg: "复制成功");
                    },
                  ),
                ),
                Container(width: ScreenUtil.getInstance().setHeight(DP_50)),
                new Container(
                  height: ScreenUtil.getInstance().setHeight(DP_60),
                  decoration: new BoxDecoration(
                      color: mainColor,
                      border: Border.all(color: mainColor, width: 1),
                      borderRadius: BorderRadius.circular(5)),
                  padding: EdgeInsets.fromLTRB(
                      ScreenUtil.getInstance().setHeight(DP_30),
                      0,
                      ScreenUtil.getInstance().setHeight(DP_30),
                      0.0),
                  child: new FlatButton(
                    child: new Padding(
                      padding: EdgeInsets.all(0.0),
                      child: new Text(
                        "分享海报",
                        style: new TextStyle(
                            color: white,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE)),
                      ),
                    ),
                    onPressed: () {
                      if (isShow && Platform.isAndroid) {
                        Fluttertoast.showToast(msg: "安装微信客户端后才能分享哦");
                        return;
                      }
                      showDialog(
                          context: context,
                          barrierDismissible: false,
                          builder: (_) {
                            return new NetLoadingDialog(
                              loadingText: "分享中...",
                              bgColor: Color.fromARGB(255, 0, 0, 0),
                              requestCallBack: null,
                              outsideDismiss: false,
                            );
                          });
                      _capturePng(WechatScene.SESSION);
                    },
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  void _listenShareMsg(WechatSdkResp resp) {
    if (Platform.isIOS) {
      if (resp.errorCode == 0) {
        Fluttertoast.showToast(msg: "分享成功");
      } else {
        Fluttertoast.showToast(msg: "分享失败");
      }
    }
  }
}
